package com.fintech.pangu.generator.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fintech.pangu.commons.api.BaseResponse;
import com.fintech.pangu.generator.entity.TableInfomation;
import com.fintech.pangu.generator.qo.DataBaseInfoRequest;
import com.fintech.pangu.generator.service.GeneratorService;
import com.fintech.pangu.generator.util.GeneratorUtil;
import com.fintech.pangu.generator.util.ZipUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

/**
 * @Description:
 * @Author xiexiaole
 * @Date 2019/11/7 15:11
 */
@RestController
@RequestMapping("/generator")
public class GeneratorController {

    private static Logger logger = LoggerFactory.getLogger(GeneratorController.class);


    @Autowired
    private GeneratorService generatorService;

    @GetMapping("/getTableList")
    public BaseResponse getTableList(DataBaseInfoRequest dataBaseInfoRequest){
        if(StringUtils.isEmpty(dataBaseInfoRequest.getUrl()) ||
                StringUtils.isEmpty(dataBaseInfoRequest.getUserName()) ||
                StringUtils.isEmpty(dataBaseInfoRequest.getPassword())){
            BaseResponse response = new BaseResponse();
            response.setRetCode("0002");
            response.setRetDesc("参数异常");
            return response;
        }
        List<TableInfomation> tableList = generatorService.getTableList(dataBaseInfoRequest);
        return new BaseResponse<>(tableList);
    }

    @GetMapping("/getTablePage")
    public BaseResponse getTablePage(DataBaseInfoRequest dataBaseInfoRequest){
        if(StringUtils.isEmpty(dataBaseInfoRequest.getUrl()) ||
                StringUtils.isEmpty(dataBaseInfoRequest.getUserName()) ||
                StringUtils.isEmpty(dataBaseInfoRequest.getPassword())){
            BaseResponse response = new BaseResponse();
            response.setRetCode("0002");
            response.setRetDesc("参数异常");
            return response;
        }
        IPage<List<TableInfomation>> tablePage = generatorService.getTablePage(dataBaseInfoRequest);
        return new BaseResponse<>(tablePage);
    }

    @PostMapping(value = "/generatorCode")
    public void generator(@RequestBody JSONObject object,HttpServletResponse response) throws IOException {

        //零时文件目录
        String folder=System.getProperty("java.io.tmpdir");
//        String folder = "E:/test/";
        logger.info("文件输出目录为：{}",folder);
        //1、生产代码-->文件
        String outPath = generatorService.generatorCode(object, folder);
        //2、本地文件-->压缩
        String outFile = outPath + ".zip";
        ZipUtil.zipMultiFile(outPath, outFile, false);
        //3、下载文件
        FileInputStream inputStream = null;
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream outputStream = null;
        File file = null;
        try {
            file = new File(outFile);
            inputStream = new FileInputStream(file);
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"pangu.zip\"");
            int available = inputStream.available();
            response.setHeader("Content-Length", String.valueOf(available));
            response.setContentType("application/octet-stream; charset=UTF-8");
            bufferedInputStream = new BufferedInputStream(inputStream);
            outputStream = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[4096];
            int bytesRead;
            while(-1 != (bytesRead = bufferedInputStream.read(buff, 0, buff.length))) {
                outputStream.write(buff,0,bytesRead);
                outputStream.flush();
            }
            response.flushBuffer();
        } catch (FileNotFoundException e) {
            logger.error("输出信息");
        } catch (IOException ie){

        }finally {
            if (outputStream != null){
                outputStream.close();
            }
            if (outputStream != null){
                inputStream.close();
            }
            if(bufferedInputStream != null) {
                bufferedInputStream.close();
            }
        }
        //4、删除本地文件
        GeneratorUtil.deleteFileOrDirectory(file);
        GeneratorUtil.deleteFileOrDirectory(outPath);
    }

    @GetMapping(value = "/parentVersion")
    public BaseResponse getParentVersion(){
        List<String> parentVersion = generatorService.getParentVersion();
        return new BaseResponse(parentVersion);
    }

}
